/**
 * UploadPictureAction.java
 *
 *
 * $LastChangedBy: allen $
 * $LastChangedDate: 2007-12-06 16:27:23 +0800 $
 * $Revision: 1389 $
 */
package com.myspace.view.picture;

import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.myspace.common.util.FileUtil;
import com.myspace.domain.Picture;
import com.myspace.domain.User;
import com.myspace.common.util.image.ImageUtils;
import com.myspace.service.picture.EditPictureService;
import com.myspace.service.user.UserService;
import com.myspace.view.common.Constant;
import com.myspace.view.common.DispatchBaseAction;
import com.myspace.view.common.UploadFileUtils;
import com.myspace.view.common.UserUtil;

/**
 *
 * @author Allen.Chen
 *
 */
public class UploadPictureAction extends DispatchBaseAction {

	public ActionForward view(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (!UserUtil.isLogin(request)) {
			return mapping.findForward("login");
		}
		return mapping.findForward("success");
	}

	public ActionForward upload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UploadPictureForm upForm = (UploadPictureForm) form;
		if (!UserUtil.isLogin(request)) {
			return mapping.findForward("login");
		}
		long userId = UserUtil.getUser(request).getId();
		try {
			for (int i = 0; i < Constant.UPLOAD_FILE_SIZE; i++) {
				if (upForm.getImageFile(i) != null
						&& StringUtils.isNotEmpty(upForm.getImageFile(i)
								.getFileName())) {
					this.savePicture(userId, upForm.getImageName(i), upForm
							.getImageTag(i), upForm.getImageFile(i)
							.getFileName(), upForm.getImageFile(i)
							.getInputStream());
				}
			}
			UserService userService = (UserService) getWebApplicationContext()
					.getBean("userService");
			User user = UserUtil.getUser(request);
			user.setUpdateDate(new Date());
			userService.update(user);
		} catch (Exception e) {
			getLogger().error(e);
			ActionMessages errors = new ActionMessages();
			errors.add(Globals.ERROR_KEY, new ActionMessage("系统发生异常，请联系统管理员!",
					false));
			this.saveErrors(request, errors);
			return mapping.findForward("error");
		}
		return new ActionForward("/picture/listPicture.do?tag="
				+ URLEncoder.encode(upForm.getTag(), "UTF-8"), true);
	}

	private void savePicture(Long userId, String realName, String tag,
			String fileName, InputStream is) throws Exception {
		// Creates origianl picture.
		String hashedFileName = UploadFileUtils.buildHashedFileName(fileName);
		String originalPicUrl = UploadFileUtils.buildHashedPathURL(
				hashedFileName, Constant.PICTURE_PATH);
		File originalPicFile = FileUtil.createFile(Constant.FILE_PATH
				+ File.separator + originalPicUrl);
		FileUtil.writeToFile(is, originalPicFile);

		// Gets preview picture name.
		String previewPicName = hashedFileName;
		int pos = previewPicName.lastIndexOf(".");
		if (pos > 0) {
			previewPicName = previewPicName.substring(0, pos);
		}
		previewPicName = previewPicName + Constant.PREVIEW_EXT;

		// Creates preview picture.
		String previewPicUrl = UploadFileUtils.buildHashedPathURL(
				previewPicName, Constant.PICTURE_PATH);
		File previewPicFile = FileUtil.createFile(Constant.FILE_PATH
				+ File.separator + previewPicUrl);
		ImageUtils.bulidImage(originalPicFile, previewPicFile);

		// Fills picture's attributes.
		Picture picture = new Picture();
		picture.setCreateDate(new Date(System.currentTimeMillis()));
		if (StringUtils.isEmpty(realName)) {
			picture.setName(fileName);
		} else {
			picture.setName(realName);
		}
		picture.setOriginalPicPath(originalPicUrl);
		picture.setPreviewPicPath(previewPicUrl);

		// Add picture to database.
		EditPictureService editPictureService = (EditPictureService) getWebApplicationContext()
				.getBean("editPictureService");
		if (StringUtils.isEmpty(tag)) {
			tag = Constant.DEFAULT_TAG;
		}
		String[] tags = null;
		tags = tag.split(",");
		for (int i = 0; i < tags.length; i++) {
			tags[i] = tags[i].toUpperCase();
		}
		editPictureService.addPicture(userId, picture, tags);
	}

}
